{% extends '_admin.html' %}

{% set device='LED屏幕' %}

{% block main_contain %}
<div class="row" id="GateDevice">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
              <div class="btn-group">
                <button type="button" class="btn btn-info" data-toggle="modal" data-target="#AddModal">
                  <i class="fas fa-plus"></i> 新增
                </button>
                <button type="button" class="btn btn-info" data-toggle="modal" data-target="#FilterModal">
                  <i class="fas fa-search"></i> 篩選
                </button>
                <button type="button" class="btn btn-info" @click="reset_filters"><i class="fas fa-undo"></i> 重置</button>
              </div>
            </div>
            <!-- /.card-header -->
            <div class="card-body">
              <table id="DeviceTable" class="table table-bordered table-hover text-center">
                <thead>
                <tr>
                  {% for k, v in ColumnName.items() %}
                  {% if k not in ('UserName','Password','Serial') %}
                  <th>{{ v }}</th>
                  {% endif %}
                  {% endfor %}
                  <th>操作</th>
                </tr>
                </thead>
                <tbody>
                    {% if Device %}
                    {% for i in Device %}
                    <tr style="font-size: x-large;">
                      <td>
                        <a href="#" data-toggle="modal" data-target="#EditModal" data-device_id="{{ i.LEDID }}">{{ i.LEDID }}</a>
                      </td>
                      <td>{{ i.GateID }}</td>
                      <td>{{ GateTypes[i.GateType] }}</td>
                      <td>{{ i.GateName }}</td>
                      <td>{{ i.Position }}</td>
                      <td>{{ i.LEDAddr }}</td>
                      <td>
                        <button class="btn btn-sm btn-info">測試</button>
                        <button class="btn btn-sm btn-danger" data-toggle="modal" data-target="#DeleteModal" 
                        data-device_id="{{ i.LEDID }}" data-device_addr="{{ i.LEDID }}">刪除</button>
                      </td>
                    </tr>
                    {% endfor %}
                    {% endif %}
                </tbody>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
    </div>
    <!--操作对话框-->
  <div class="modal fade" id="AddModal">
    <div class="modal-dialog modal-dialog-centered">
      <form id="AddForm">
        <div class="modal-content">
          <div class="modal-header justify-content-center">
              <h4 class="modal-title text-danger">新增{{ device }}</h4>
          </div>
          <div class="modal-body text-center">
            <div v-for="(val, key) in DeviceAdd" class="form-group row">
              <label class="col-sm-4 col-form-label text-center">{[ ColumnName[key] ]}：</label>
              <div class="col-sm-8">
                  <select v-if="key=='GateID'" v-model="DeviceAdd[key]" class="form-control" :name="key" style="font-size: large;" @change="add_gate_select">
                    <option  v-if="GateExists.length>0" v-for="Gate in GateExists" :value="Gate.GateID">{[ Gate.GateID ]}</option>
                  </select>
                  <input v-else v-model="DeviceAdd[key]" class="form-control" type="text" :name="key" style="font-size: large;"
                  :readonly="['GateName','GateType','Position'].includes(key)?'readonly':false">
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-between">
              <button type="submit" class="btn btn-success">確認</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </form>
    </div>
  <!-- /.modal-dialog -->
  </div>

  <div class="modal fade" id="EditModal">
    <div class="modal-dialog modal-dialog-centered">
      <form id="EditForm">
        <div class="modal-content">
          <div class="modal-header justify-content-center">
              <h4 class="modal-title text-danger">{{ device }}設定</h4>
          </div>
          <div class="modal-body text-center">
            <div v-for="(val, key) in DeviceEdit" class="form-group row">
              <label class="col-sm-4 col-form-label text-center">{[ ColumnName[key] ]}：</label>
              <div class="col-sm-8">
                <select v-if="key=='GateID'" v-model="DeviceEdit[key]" class="form-control" :name="key" style="font-size: large;" @change="edit_gate_select">
                  <option  v-if="GateExists.length>0" v-for="Gate in GateExists" :value="Gate.GateID">{[ Gate.GateID ]}</option>
                </select>
                <input v-else v-model="DeviceEdit[key]" class="form-control" type="text" :name="key" style="font-size: large;"
                :readonly="['GateName','GateType','Position','Serial','LEDID'].includes(key)?'readonly':false">
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-between">
              <button type="submit" class="btn btn-success">確認</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </form>
    </div>
  <!-- /.modal-dialog -->
  </div>

  <div class="modal fade" id="FilterModal">
    <div class="modal-dialog modal-dialog-centered">
      <form id="FilterForm">
        <div class="modal-content">
          <div class="modal-header justify-content-center">
              <h4 class="modal-title text-danger">篩選{{ device }}</h4>
          </div>
          <div class="modal-body text-center">
            <div v-for="(val, key) in DeviceFilter" class="form-group row">
              <label class="col-sm-4 col-form-label text-center">{[ ColumnName[key] ]}：</label>
              <div class="col-sm-8">
                  <select v-if="key=='GateType'" v-model="DeviceFilter[key]" class="form-control" :name="key" style="font-size: large;">
                    <option  v-for="(val, key) in GateTypes" :value="key">{[ val ]}</option>
                  </select>
                  <input v-else v-model="DeviceFilter[key]" class="form-control" type="text" :name="key" style="font-size: large;">
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-success" data-dismiss="modal" @click="commit_data('Filter')">查找</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </form>
    </div>
  <!-- /.modal-dialog -->
  </div>

  <div class="modal fade" id="DeleteModal">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
        <div class="modal-header justify-content-center">
            <h4 class="modal-title text-danger"><i class="fas fa-exclamation-triangle"></i> 請注意</h4>
        </div>
        <div class="modal-body text-center">
            <p class="h5">刪除<strong class="text-danger">{[ DeviceDelete.LEDAddr ]}</strong>的LED屏嗎？</p>
        </div>
        <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-success" @click="commit_data('Delete')">確認</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        </div>
        </div>
        <!-- /.modal-content -->
    </div>
  <!-- /.modal-dialog -->
  </div>
</div>

<a id="scrobutton" href="#" class="btn btn-primary back-to-top" role="button" aria-label="Scroll to top" style="margin-bottom: 45px; display: none;">
  <i class="fas fa-chevron-up"></i>
</a>
{% endblock %}


{% block scripts %}
{{ super() }}
<script>
    // LED
    var GateDevice = new Vue({
        el: '#GateDevice',
        delimiters: ['{[', ']}'],
        data: {
          DeviceAdd: {
            GateID: '',
            GateType: '',
            GateName: '',
            Position: '',
            LEDAddr: '',
          },
          DeviceEdit: {
            LEDID: '',
            GateID: '',
            GateType: '',
            GateName: '',
            Position: '',
            LEDAddr: '',
          },
          DeviceFilter: {
            GateType: '',
            GateName: '',
            Position: '',
          },
          DeviceDelete:{
            LEDID: '',
            LEDAddr: '',
          },
          ColumnName: JSON.parse('{{ ColumnNameJSON|safe }}'),
          GateExists: JSON.parse('{{ ValidGatesObj|safe }}'),
          GateTypes: JSON.parse('{{ PageJSON.GateTypes|safe }}'),
        },
        methods: {
          // 新增相机选择事件
          add_gate_select(){
            if(this.GateExists.length>0){
              let gate_id = this.DeviceAdd.GateID
              this.GateExists.forEach(gate => {
                if(gate_id==gate.GateID){
                  this.DeviceAdd.GateType=gate.GateType
                  this.DeviceAdd.GateName=gate.GateName
                  this.DeviceAdd.Position=gate.Position
                }})}
          },
          // 编辑相机选择事件
          edit_gate_select(){
            if(this.GateExists.length>0){
              let gate_id = this.DeviceEdit.GateID
              this.GateExists.forEach(gate => {
                if(gate_id==gate.GateID){
                  this.DeviceEdit.GateType=gate.GateType
                  this.DeviceEdit.GateName=gate.GateName
                  this.DeviceEdit.Position=gate.Position
                }})}
          },
          // 获取当前设备
          device_selected(device_id){
            axios.post("{{ url_for('devices.led') }}", {GetDevice: device_id})
            .then(response => {
              if(response.status==200){
                let ret = response.data
                if(ret.__proto__==Object.prototype){
                  for(key in this.DeviceEdit){if(ret.hasOwnProperty(key)){this.DeviceEdit[key]=ret[key]}}
                }
              }else{AppMessage.fire({icon: 'error', text: '請求錯誤，請聯係管理員'})}
            })
            .catch(function (error) {alert(error)})
          },
          // 获取当前查询条件
          current_filters(){
            axios.post("{{ url_for('devices.led') }}", {GetFilter: 'LEDFilter'})
            .then(response => {
              if(response.status==200){
                let ret = response.data
                if(ret.__proto__==Object.prototype){
                  for(key in this.DeviceFilter){if(ret.hasOwnProperty(key)){this.DeviceFilter[key]=ret[key]}}
                }
              }else{AppMessage.fire({icon: 'error', text: '請求錯誤，請聯係管理員'})}
            })
            .catch(function (error) {alert(error)})
          },
          // 重置
          reset_filters(){
            axios.post("{{ url_for('devices.led') }}", {ResetFilter: 'LEDFilter'})
            .then(response => {if(response.status==200){setTimeout("window.location.reload()")}})
            .catch(function (error) {alert(error)})
          },
          // 提交数据
          commit_data(name){
              let p_data = ''
              switch(name){
                case 'Add': p_data={Add: this.DeviceAdd};break
                case 'Update': p_data={Update: this.DeviceEdit};break
                case 'Delete': p_data={Delete: this.DeviceDelete};break
                case 'Filter': p_data={SetFilter: this.DeviceFilter};break
              }
              axios.post("{{ url_for('devices.led') }}", p_data)
              .then(response => {
                if(response.status==200){
                  let ret = response.data
                  AppMessage.fire({icon: ret.icon, text: ret.text})
                  if(ret.icon=='success'){
                    if($('#AddModal').css('display')=="block"){$("#AddModal").modal('toggle')}
                    if($('#EditModal').css('display')=="block"){$("#EditModal").modal('toggle')}
                    if($('#DeleteModal').css('display')=="block"){$("#DeleteModal").modal('toggle')}
                    setTimeout("window.location.reload()", 2000);
                  }
                }else{AppMessage.fire({icon: 'error', text: '操作錯誤，請聯係管理員'})}
              })
              .catch(function (error) {alert(error)})
            }
        },
        mounted: function(){
          // 校验新增
          $('#AddForm').validate({
            rules: {
              GateType: {required: true},
              GateName: {required: true},
              VehicleType: {required: true},
              CameraAddr: {required: true},
              UserName: {required: true},
              Password: {required: true},
            },
            errorElement: 'span',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.col-sm-8').append(error);
              },
            highlight: function (element, errorClass, validClass) {$(element).addClass('is-invalid')},
            unhighlight: function (element, errorClass, validClass) {$(element).removeClass('is-invalid')},
            // 提交
            submitHandler: function (){
              GateDevice.commit_data('Add')
            },
          });
          // 校验编辑
          $('#EditForm').validate({
            rules: {
              GateType: {required: true},
              GateName: {required: true},
              VehicleType: {required: true},
              CameraAddr: {required: true},
              UserName: {required: true},
              Password: {required: true},
            },
            errorElement: 'span',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.col-sm-8').append(error);
              },
            highlight: function (element, errorClass, validClass) {$(element).addClass('is-invalid')},
            unhighlight: function (element, errorClass, validClass) {$(element).removeClass('is-invalid')},
            // 提交
            submitHandler: function (){
              GateDevice.commit_data('Update')
            },
          });
          // 数据表
          $('#DeviceTable').DataTable({
              language: {url: "{{ url_for('static', filename='plugins/datatables/zh_hk.json') }}"},
              responsive: true,
              autoWidth: false,
            });

          // 编辑設備
          $("#EditModal").on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget) 
            let device_id = button.data('device_id')
            GateDevice.device_selected(device_id)
          });

          // 删除設備
          $("#DeleteModal").on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget) 
            let device_id = button.data('device_id')
            let device_addr = button.data('device_addr')
            GateDevice.DeviceDelete.LEDID = device_id
            GateDevice.DeviceDelete.LEDAddr = device_addr
          });

          // 筛选对话
          $("#FilterModal").on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget) 
            GateDevice.current_filters()
          });
        }
    });
    // 当网页向下滑动 20px 出现"返回顶部" 按钮
    window.onscroll = function() {
      if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {$("#scrobutton").css("display", "block")}
      else {$("#scrobutton").css("display", "none")}
    };
</script>
{% endblock %}

